package com.liang.demo.shiro;

import com.liang.demo.po.Admin;
import com.liang.demo.service.AdminService;
import com.liang.demo.service.ResourceService;
import com.liang.demo.service.RoleService;
import com.liang.demo.util.ApplicationContextUtils;
import com.liang.demo.util.JwtUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author 陈琪亮
 * @version 1.0
 * @date 2021/3/19 15:37
 */
@Component
public class CustomRealm extends AuthorizingRealm {

    Logger log = LoggerFactory.getLogger(Logger.class);

    @Override
    public void setName(String name) {
        super.setName("REALM");
    }

    /**
     * 必须重写此方法，不然会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        String adminId = JwtUtil.getDate(token);
//        //token校验
        if (adminId == null || !JwtUtil.verify(token, adminId)) {
            throw new AuthenticationException("token认证失败！");
        }
        AdminService adminService = (AdminService) ApplicationContextUtils.getBean("adminServiceImpl");
        Admin admin = adminService.getAdminInfo(Long.parseLong(adminId));
        if (admin == null) {
            throw new AuthenticationException("该用户不存在！");
        } else {
            return new SimpleAuthenticationInfo(token, token, getName());
        }
    }


    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取用户角色信息，权限信息
        String adminId = JwtUtil.getDate(principals.toString());
        RoleService roleService = (RoleService) ApplicationContextUtils.getBean("roleServiceImpl");
        ResourceService resourceService = (ResourceService) ApplicationContextUtils.getBean("resourceServiceImpl");
        //获取用户角色
        Set<String> roleSet = roleService.getRolesByAdminId(adminId);
//        //获取用户权限字符串
        Set<String> permissions = resourceService.getPermissionByUserId(adminId);
        info.setRoles(roleSet);
        info.setStringPermissions(permissions);
        return info;
    }
}

